﻿using System.Linq.Expressions;

public class IfAstTree : LuaAstTree
{
    public LuaAstTree Expression { get; }
    public BlockAstTree Then { get; set; }
    public BlockAstTree Else { get; set; }
    public IfAstTree(LuaAstTree expression, BlockAstTree then, BlockAstTree @else)
    {
        Expression = expression;
        Then = then;
        Else = @else;
    }
    public override void WriteTo(ICodeWriter writer)
    {
        if (Then == null)
        {
            writer.Code("if not(");
            Expression.WriteTo(writer);
            writer.CodeLine(") then");
            writer.Indent++;
            Else.WriteTo(writer);
            writer.Indent--;
            writer.Code("end");
        }
        else
        {
            writer.Code("if ");
            Expression.WriteTo(writer);
            writer.CodeLine(" then");
            writer.Indent++;
            if (Then != null)
            {
                Then.WriteTo(writer);
                writer.Line();

            }
            if (Else != null)
            {
                var idElseIf = Else.Statements.Count == 1 && Else.Statements[0] is IfAstTree;
                if (idElseIf)
                {
                    writer.Indent--;
                    writer.Code("else");
                    Else.WriteTo(writer);
                }
                else
                {
                    writer.Indent--;
                    writer.CodeLine("else");
                    writer.Indent++;
                    Else.WriteTo(writer);
                    writer.Line();
                    writer.Indent--;
                    writer.Code("end");
                }
            }
            else
            {
                writer.Indent--;
                writer.Code("end");
            }
        }

    }
}